package com.hui.server.config.jwt;

/**
 * @BelongsProject: SpringSecurity-jwt
 * @BelongsPackage: com.hui.jwt.security
 * @Author: HUI
 * @CreateTime: 2022-04-02 21:08
 * @Description:
 */

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hui.server.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义无权访问类
 */
@Component
@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        System.err.println("权限不足");
        response.setContentType("text/json;charset=utf-8");
        log.error("用户访问没有权限的资源：{}",accessDeniedException.getMessage());
        Result<?> result = Result.error(String.valueOf(HttpStatus.FORBIDDEN.value()), "对不起，权限不足！");
        String value = new ObjectMapper().writeValueAsString(result);
        response.getWriter().println(value);
    }
}
